import { useEffect } from 'react';
import { useRouter } from '@/router/hooks';
import { message } from 'antd';
import { logout } from './authUtils';
import Cookies from 'js-cookie';
import { jwtDecode } from 'jwt-decode';

import userStore, { useUserActions, useUserInfo } from '@/store/userStore';
import { useTourActions } from '@/store/tourStore';
import { StorageEnum } from '@/types/enum';
import { CircleLoading } from '@/components/loading';

const { VITE_LOGOUT_PAGE: LOGINPAGE } = import.meta.env;
const { VITE_AUTH_FLAG: AUTHFLAG } = import.meta.env;
const { VITE_TOKEN: VITETOKEN } = import.meta.env;
const authFlag = AUTHFLAG === 'true' ? true : false;

const AuthPage = () => {
  const { replace } = useRouter();

  const { setUserToken, setUserInfo } = useUserActions();
  const userInfo = useUserInfo();

  const { setIsFirstLogin } = useTourActions();

  const init = async () => {
    try {
      // userInfo.isFirstLogin && setIsFirstLogin(userInfo.isFirstLogin);
      const token = Cookies.get(VITETOKEN);
      if (!token) {
        if ((authFlag) && LOGINPAGE) {
          window.location.href = LOGINPAGE;
        } else {
          replace('/login');
        }
      } else {
        const decodedToken = jwtDecode(token);
        // setIsFirstLogin(decodedToken?.isFirstLogin || false);

        let mergeUser = {
          ...userInfo,
          ...decodedToken
        }

        setUserInfo(mergeUser);
        setUserToken({ accessToken: token, refreshToken: token });
      }

      replace(`/worklayouts/`)
    } catch (error) {
      message.error('请联系工程师配置应用信息！');
      logout();
    }
  };

  useEffect(() => {
    init();
  }, []);

  return <CircleLoading />;
};

export default AuthPage;
